<template>
  <div class="app-container">
    <!-- 简化的搜索表单 - 只保留4个常用字段 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="活动标题" prop="activityTitle">
        <el-input
          v-model="queryParams.activityTitle"
          placeholder="请输入活动标题"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动地点" prop="activityLocation">
        <el-input
          v-model="queryParams.activityLocation"
          placeholder="请输入活动地点"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布者" prop="publisherNickname">
        <el-input
          v-model="queryParams.publisherNickname"
          placeholder="请输入发布者昵称"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:activities:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:activities:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:activities:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:activities:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 优化的数据表格 - 精简字段，使用合适的展示组件 -->
    <el-table 
      v-loading="loading" 
      :data="activitiesList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动ID" align="center" prop="activityId" width="80" />
      <el-table-column label="活动封面" align="center" prop="activityImages" width="100">
        <template slot-scope="scope">
          <el-image 
            v-if="scope.row.activityImages && getFirstImage(scope.row.activityImages)"
            style="width: 60px; height: 60px; border-radius: 4px"
            :src="getFirstImage(scope.row.activityImages)" 
            :preview-src-list="getImageList(scope.row.activityImages)"
            fit="cover">
          </el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="活动标题" align="center" prop="activityTitle" min-width="180" show-overflow-tooltip />
      <el-table-column label="活动地点" align="center" prop="activityLocation" min-width="150" show-overflow-tooltip />
      <el-table-column label="参与人数" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.activityCurrentParticipants || 0 }}/{{ scope.row.activityMaxParticipants }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布者" align="center" width="120">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-avatar 
              v-if="scope.row.publisherAvatar"
              :size="30" 
              :src="scope.row.publisherAvatar"
              style="margin-right: 8px">
            </el-avatar>
            <span>{{ scope.row.publisherNickname }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="活动标签" align="center" min-width="150">
        <template slot-scope="scope">
          <el-tag 
            v-for="(tag, index) in getTagList(scope.row.activityTags)" 
            :key="index" 
            size="small" 
            style="margin: 2px;">
            {{ tag }}
          </el-tag>
          <span v-if="!scope.row.activityTags">-</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="activityPublishTime" min-width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityPublishTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" min-width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:activities:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:activities:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 优化的添加/修改弹窗 - 使用tabs分组 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="活动封面" prop="activityImages">
                  <image-upload 
                    v-model="form.activityImages" 
                    :limit="5"
                    :fileSize="5"
                    :isShowTip="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动标题" prop="activityTitle">
                  <el-input 
                    v-model="form.activityTitle" 
                    placeholder="请输入活动标题" 
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动地点" prop="activityLocation">
                  <el-input v-model="form.activityLocation" placeholder="请输入活动地点" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动发布时间" prop="activityPublishTime">
                  <el-date-picker 
                    clearable 
                    style="width: 100%"
                    v-model="form.activityPublishTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择发布时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最大参与人数" prop="activityMaxParticipants">
                  <el-input-number 
                    v-model="form.activityMaxParticipants" 
                    :min="1" 
                    :max="10000"
                    placeholder="最大人数" 
                    style="width: 100%" 
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="活动详情" prop="activityDetails">
                  <el-input 
                    v-model="form.activityDetails" 
                    type="textarea" 
                    :rows="4"
                    placeholder="请输入活动详情描述"
                    maxlength="2000"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 发布者信息 -->
          <el-tab-pane label="发布者信息" name="publisher">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="发布者ID" prop="publisherId">
                  <el-input-number 
                    v-model="form.publisherId" 
                    :min="1"
                    placeholder="发布者ID" 
                    style="width: 100%" 
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发布者昵称" prop="publisherNickname">
                  <el-input v-model="form.publisherNickname" placeholder="请输入发布者昵称" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="发布者头像" prop="publisherAvatar">
                  <image-upload 
                    v-model="form.publisherAvatar" 
                    :limit="1"
                    :fileSize="2"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="个性签名" prop="publisherSignature">
                  <el-input 
                    v-model="form.publisherSignature" 
                    type="textarea" 
                    :rows="3"
                    placeholder="请输入发布者个性签名"
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="发布者标签" prop="publisherTags">
                  <el-tag
                    v-for="tag in publisherTagsList"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    @close="handlePublisherTagClose(tag)"
                    style="margin-right: 10px;">
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="inputPublisherTagVisible"
                    v-model="inputPublisherTagValue"
                    ref="savePublisherTagInput"
                    size="small"
                    style="width: 120px;"
                    @keyup.enter.native="handleInputPublisherTagConfirm"
                    @blur="handleInputPublisherTagConfirm">
                  </el-input>
                  <el-button v-else size="small" @click="showPublisherTagInput">+ 新标签</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 扩展信息 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="活动标签" prop="activityTags">
                  <el-tag
                    v-for="tag in activityTagsList"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    @close="handleActivityTagClose(tag)"
                    style="margin-right: 10px;">
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="inputActivityTagVisible"
                    v-model="inputActivityTagValue"
                    ref="saveActivityTagInput"
                    size="small"
                    style="width: 120px;"
                    @keyup.enter.native="handleInputActivityTagConfirm"
                    @blur="handleInputActivityTagConfirm">
                  </el-input>
                  <el-button v-else size="small" @click="showActivityTagInput">+ 新标签</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="当前参与人数" prop="activityCurrentParticipants">
                  <el-input-number 
                    v-model="form.activityCurrentParticipants" 
                    :min="0"
                    placeholder="当前人数" 
                    style="width: 100%" 
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listActivities, getActivities, delActivities, addActivities, updateActivities } from "@/api/system/activities";

export default {
  name: "Activities",
  components: {
    ImageUpload: () => import("@/components/ImageUpload")
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动信息表格数据
      activitiesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前激活的标签页
      activeTab: 'basic',
      // 活动标签输入
      inputActivityTagVisible: false,
      inputActivityTagValue: '',
      activityTagsList: [],
      // 发布者标签输入
      inputPublisherTagVisible: false,
      inputPublisherTagValue: '',
      publisherTagsList: [],
      // 查询参数（简化后）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityTitle: null,
        activityLocation: null,
        publisherNickname: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityTitle: [
          { required: true, message: "活动标题不能为空", trigger: "blur" },
          { min: 2, max: 100, message: "活动标题长度在 2 到 100 个字符", trigger: "blur" }
        ],
        activityMaxParticipants: [
          { required: true, message: "最大参与人数不能为空", trigger: "blur" }
        ],
        publisherId: [
          { required: true, message: "发布者用户ID不能为空", trigger: "blur" }
        ],
        publisherNickname: [
          { required: true, message: "发布者昵称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询活动信息列表 */
    getList() {
      this.loading = true;
      listActivities(this.queryParams).then(response => {
        this.activitiesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    
    // 表单重置
    reset() {
      this.form = {
        activityId: null,
        activityTitle: null,
        activityImages: null,
        activityType: null,
        activityTags: null,
        activityDetails: null,
        activityLocation: null,
        activityCoordinates: null,
        activityPublishTime: null,
        activityCategory: null,
        activityRestriction: null,
        activityCurrentParticipants: 0,
        activityMaxParticipants: null,
        publisherId: null,
        publisherAvatar: null,
        publisherNickname: null,
        publisherSignature: null,
        publisherTags: null,
        activityStatus: null,
        status: null,
        extraData: null
      };
      this.activityTagsList = [];
      this.publisherTagsList = [];
      this.activeTab = 'basic';
      this.resetForm("form");
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.activityId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动信息";
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const activityId = row.activityId || this.ids
      getActivities(activityId).then(response => {
        this.form = response.data;
        
        // 处理 JSON 字段 - 活动标签
        if (this.form.activityTags) {
          this.activityTagsList = typeof this.form.activityTags === 'string' 
            ? JSON.parse(this.form.activityTags) 
            : this.form.activityTags;
        }
        
        // 处理 JSON 字段 - 发布者标签
        if (this.form.publisherTags) {
          this.publisherTagsList = typeof this.form.publisherTags === 'string' 
            ? JSON.parse(this.form.publisherTags) 
            : this.form.publisherTags;
        }
        
        // 处理 ImageUpload 的 JSON 字段 - 活动图片（转换为逗号分隔字符串）
        if (this.form.activityImages) {
          const urls = typeof this.form.activityImages === 'string' 
            ? JSON.parse(this.form.activityImages) 
            : this.form.activityImages;
          this.form.activityImages = Array.isArray(urls) ? urls.join(',') : urls;
        }
        
        this.open = true;
        this.title = "修改活动信息";
      });
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitForm = { ...this.form };
          
          // 处理标签字段 - 转为 JSON
          submitForm.activityTags = this.activityTagsList.length > 0 
            ? JSON.stringify(this.activityTagsList) 
            : null;
          submitForm.publisherTags = this.publisherTagsList.length > 0 
            ? JSON.stringify(this.publisherTagsList) 
            : null;
          
          // 处理 ImageUpload 的图片字段 - 转为 JSON 数组
          if (submitForm.activityImages && typeof submitForm.activityImages === 'string') {
            const urlArray = submitForm.activityImages
              .split(',')
              .map(url => url.trim())
              .filter(url => url);
            submitForm.activityImages = urlArray.length > 0 
              ? JSON.stringify(urlArray) 
              : null;
          }
          
          if (submitForm.activityId != null) {
            updateActivities(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActivities(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const activityIds = row.activityId || this.ids;
      this.$modal.confirm('是否确认删除活动信息编号为"' + activityIds + '"的数据项？').then(function() {
        return delActivities(activityIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/activities/export', {
        ...this.queryParams
      }, `activities_${new Date().getTime()}.xlsx`)
    },
    
    /** 活动标签相关方法 */
    handleActivityTagClose(tag) {
      this.activityTagsList.splice(this.activityTagsList.indexOf(tag), 1);
    },
    showActivityTagInput() {
      this.inputActivityTagVisible = true;
      this.$nextTick(() => {
        this.$refs.saveActivityTagInput.$refs.input.focus();
      });
    },
    handleInputActivityTagConfirm() {
      let inputActivityTagValue = this.inputActivityTagValue;
      if (inputActivityTagValue && !this.activityTagsList.includes(inputActivityTagValue)) {
        this.activityTagsList.push(inputActivityTagValue);
      }
      this.inputActivityTagVisible = false;
      this.inputActivityTagValue = '';
    },
    
    /** 发布者标签相关方法 */
    handlePublisherTagClose(tag) {
      this.publisherTagsList.splice(this.publisherTagsList.indexOf(tag), 1);
    },
    showPublisherTagInput() {
      this.inputPublisherTagVisible = true;
      this.$nextTick(() => {
        this.$refs.savePublisherTagInput.$refs.input.focus();
      });
    },
    handleInputPublisherTagConfirm() {
      let inputPublisherTagValue = this.inputPublisherTagValue;
      if (inputPublisherTagValue && !this.publisherTagsList.includes(inputPublisherTagValue)) {
        this.publisherTagsList.push(inputPublisherTagValue);
      }
      this.inputPublisherTagVisible = false;
      this.inputPublisherTagValue = '';
    },
    
    /** 工具方法 - 获取图片列表 */
    getImageList(imagesJson) {
      if (!imagesJson) return [];
      try {
        const images = typeof imagesJson === 'string' ? JSON.parse(imagesJson) : imagesJson;
        return Array.isArray(images) ? images : [];
      } catch (e) {
        return [];
      }
    },
    
    /** 工具方法 - 获取第一张图片 */
    getFirstImage(imagesJson) {
      const images = this.getImageList(imagesJson);
      return images.length > 0 ? images[0] : null;
    },
    
    /** 工具方法 - 获取标签列表 */
    getTagList(tagsJson) {
      if (!tagsJson) return [];
      try {
        const tags = typeof tagsJson === 'string' ? JSON.parse(tagsJson) : tagsJson;
        return Array.isArray(tags) ? tags : [];
      } catch (e) {
        return [];
      }
    }
  }
};
</script>
